package pl.register.android.database.crud;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import pl.register.android.database.dao.TaskDao;
import pl.register.android.database.tables.TaskDBTable;
import pl.register.android.task.Task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Mateusz Strzelecki
 * @since 2013-04-26
 */
public class TaskCRUD implements TaskDao {

    private SQLiteDatabase database;

    public TaskCRUD(SQLiteDatabase database) {
        this.database = database;
    }

    @Override
    public Task save(Task task) {
        Task taskSaved;
        if (task.isPersisted()) {
            taskSaved = update(task);
        } else {
            taskSaved = insert(task);
        }
        return taskSaved;
    }

    private Task insert(Task task) {
        ContentValues insertValues = new ContentValues();
        insertValues.put(TaskDBTable.TITLE, task.getTitle());
        insertValues.put(TaskDBTable.DESCRIPTION, task.getMessage());
        insertValues.put(TaskDBTable.CREATION_DATE_MS, task.getCreationDateInMs());
        long rowId = database.insert(TaskDBTable.TABLE_NAME, null, insertValues);
        task.setId(rowId);
        return task;
    }

    private Task update(Task task) {
        String where = TaskDBTable.ID + " = " + task.getId();
        ContentValues updateValues = new ContentValues();
        updateValues.put(TaskDBTable.TITLE, task.getTitle());
        updateValues.put(TaskDBTable.DESCRIPTION, task.getMessage());
        database.update(TaskDBTable.TABLE_NAME, updateValues, where, null);
        return task;
    }

    @Override
    public List<Task> getTasks() {
        List<Task> tasks = new ArrayList<Task>();
        Cursor cursor = database.query(TaskDBTable.TABLE_NAME, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            Long taskId = cursor.getLong(cursor.getColumnIndex(TaskDBTable.ID));
            String taskTitle = cursor.getString(cursor.getColumnIndex(TaskDBTable.TITLE));
            String taskDetails = cursor.getString(cursor.getColumnIndex(TaskDBTable.DESCRIPTION));
            long dateInMs = cursor.getLong(cursor.getColumnIndex(TaskDBTable.CREATION_DATE_MS));
            tasks.add(new Task(taskId, taskTitle, taskDetails, new Date(dateInMs)));
        }
        cursor.close();
        return tasks;
    }

    @Override
    public void delete(Task task) {
        String where = TaskDBTable.ID + " = " + task.getId();
        int res = database.delete(TaskDBTable.TABLE_NAME, where, null);
    }
}